package com.ruoyi.web.controller.hazard;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.file.service.impl.FileInfoServiceImpl;
import com.ruoyi.hazard.domain.HazardAlarmInfo;
import com.ruoyi.hazard.domain.HazardInfo;
import com.ruoyi.hazard.domain.dto.HazardInfoDto;
import com.ruoyi.hazard.domain.qo.HazardInfoQo;
import com.ruoyi.hazard.domain.vo.*;
import com.ruoyi.hazard.service.HazardAlarmInfoService;
import com.ruoyi.hazard.service.HazardInfoService;
import com.ruoyi.hazard.service.HazardTrackInfoService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags="隐患管理")
@Slf4j
@RestController
@RequestMapping("/hazard")
public class HazardController extends BaseController {

    @Resource
    private HazardInfoService hazardInfoService;
    @Resource
    private HazardTrackInfoService hazardTrackInfoService;
    @Resource
    private FileInfoServiceImpl fileInfoService;

    @Autowired
    private HazardAlarmInfoService hazardAlarmInfoService;

    @ApiOperation("隐患数量分析")
    @PostMapping("/getHazardDashboard")
    @ApiImplicitParam(name = "deptId", value = "所属单位", required = false, dataType = "long", paramType = "query", dataTypeClass = Long.class)
    public R<List<HazardAmountAnalysisVo>> getHazardDashboard(@RequestParam(required = false) Long deptId) {
        if(deptId == null){
            deptId = SecurityUtils.getDeptId();
        }
        List<HazardAmountAnalysisVo> vo = hazardInfoService.getHazardAmountAnalysis(deptId);
        return R.ok(vo);
    }

    @ApiOperation("隐患分类统计")
    @PostMapping("/getHazardTypeStatistics")
    @ApiImplicitParam(name = "deptId", value = "所属单位", required = false, dataType = "long", paramType = "form", dataTypeClass = Long.class)
    public R<List<HazardStatisticsVo>> getHazardTypeStatistics(@RequestParam(required = false) Long deptId) {
            if(deptId == null){
                deptId = SecurityUtils.getDeptId();
            }
            List<HazardStatisticsVo> list = hazardInfoService.getHazardTypeStatistics(deptId);
            return R.ok(list);
    }

    @ApiOperation("隐患等级统计")
    @PostMapping("/getHazardLevelStatistics")
    @ApiImplicitParam(name = "deptId", value = "所属单位", required = false, dataType = "long", paramType = "query", dataTypeClass = Long.class)
    public R<List<HazardStatisticsVo>> getHazardLevelStatistics(@RequestParam(required = false) Long deptId) {
        if(deptId == null){
            deptId = SecurityUtils.getDeptId();
        }
        List<HazardStatisticsVo> list = hazardInfoService.getHazardLevelStatistics(deptId);
        return R.ok(list);
    }

//    @ApiOperation("隐患分页列表")
//    @PreAuthorize("@ss.hasPermi('hazard:list')")
//    @PostMapping("/getHazardList")
//    public R<IPage<HazardInfoVo>> pageHazard(@Validated @RequestBody HazardInfoPageQo qo) {
//        IPage<HazardInfoVo> page = hazardInfoService.getPage(qo);
//        return R.ok(page);
//    }


    @ApiOperation("隐患分页列表")
    @PreAuthorize("@ss.hasPermi('hazard:list')")
    @GetMapping("/getHazardList")
    public TableDataInfo pageHazard(HazardInfoQo qo) {
        if(qo.getDeptId() == null){
            qo.setDeptId(SecurityUtils.getDeptId());
        }
        startPage();
        List<HazardInfoDto> list = hazardInfoService.getList(qo);
        TableDataInfo tableDataInfo = getDataTable(list);
        List<HazardInfoVo> listVo = list.stream().map(dto->hazardInfoService.toVo(dto)).collect(Collectors.toList());
        tableDataInfo.setRows(listVo);
        return tableDataInfo;
    }

    @ApiOperation("隐患详情")
    @PreAuthorize("@ss.hasPermi('hazard:query')")
    @GetMapping("/get/{hazardId}")
    @ApiImplicitParam(name = "hazardId", value = "隐患信息主键", required = true, dataType = "long", paramType = "path", dataTypeClass = Long.class)
    public R<HazardInfoVo> getHazard(@PathVariable Long hazardId) {
        HazardInfo hazardInfo = hazardInfoService.getById(hazardId);
//        List<HazardTrackInfoVo> hazardTracks = Optional.ofNullable(hazardTrackInfoService.list(new LambdaQueryWrapper<HazardTrackInfo>().eq(HazardTrackInfo::getHazardId, hazardId)))
//                .orElse(Collections.emptyList())
//                .stream()
//                .map(hazardTrackInfo -> {
//                    try {
//                        return hazardTrackInfoService.toVo(hazardTrackInfo);
//                    } catch (Exception e) {
//                        // 记录异常日志，根据业务需求决定是否抛出异常或返回默认值
//                        log.error("转换HazardTrackInfo到VO时发生异常", e);
//                        return null;
//                    }
//                })
//                .filter(Objects::nonNull)
//                .collect(Collectors.toList());
        HazardInfoVo vo = hazardInfoService.toVo(hazardInfo);
        //vo.setHazardTracks(hazardTracks);
        return R.ok(vo);
    }

    @PreAuthorize("@ss.hasPermi('hazard:add')")
    @ApiOperation("新增隐患信息")
    @Log(title = "隐患信息", businessType = BusinessType.INSERT)
    @PostMapping("/addHazard")
    public R<HazardInfoVo> addHazard(@Validated @RequestBody HazardInfoVo vo) {
        //检查日期为空 默认当前日期
        if(vo.getCheckDate() == null){
            vo.setCheckDate(new Date());
        }
        //限期为空 默认90天
        if("重大".equals(vo.getLevel()) ) {
            if(vo.getSuperviseLevel() == null){
                vo.setSuperviseLevel("省局督办");
            }
            if (vo.getDeadline() == null) {
                vo.setDeadline(DateUtils.addDays(vo.getCheckDate(), 90));
            }
        }else if("一般（黄）".equals(vo.getLevel()) && vo.getDeadline() == null){
            vo.setDeadline(DateUtils.addDays(vo.getCheckDate(), 30));
        }else if("一般（蓝）".equals(vo.getLevel()) && vo.getDeadline() == null){
            vo.setDeadline(DateUtils.addDays(vo.getCheckDate(), 5));
        }

        HazardInfo hazardInfo = hazardInfoService.toEntity(vo);
        hazardInfoService.save(hazardInfo);
        vo = hazardInfoService.toVo(hazardInfo);
        return R.ok(vo);
    }


    @PreAuthorize("@ss.hasPermi('hazard:export')")
    @PostMapping("/export")
    @Log(title = "隐患信息", businessType = BusinessType.EXPORT)
    @ApiOperation("导出隐患信息")
    public void export(HttpServletResponse response,HazardInfoQo qo){
        if(qo.getDeptId() == null){
            qo.setDeptId(SecurityUtils.getDeptId());
        }
        List<HazardInfoDto> list = hazardInfoService.getList(qo);
        List<HazardInfoVo> listVo = list.stream().map(dto->hazardInfoService.toVo(dto)).collect(Collectors.toList());
        ExcelUtil<HazardInfoVo> util = new ExcelUtil<HazardInfoVo>(HazardInfoVo.class);
        util.exportExcel(response, listVo, "隐患信息数据");
    }

    @ApiOperation("下载隐患信息文件模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<HazardInfoVo> util = new ExcelUtil<HazardInfoVo>(HazardInfoVo.class);
        util.importTemplateExcel(response, "隐患信息数据");
    }

    @PreAuthorize("@ss.hasPermi('hazard:import')")
    @ApiOperation("导入隐患信息")
    @Log(title = "隐患信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception{
        ExcelUtil<HazardInfoVo> util = new ExcelUtil<HazardInfoVo>(HazardInfoVo.class);
        List<HazardInfoVo> hazardInfoVos = util.importExcel(file.getInputStream());
        String message = hazardInfoService.importData(hazardInfoVos, updateSupport);
        return success(message);
    }


    @PreAuthorize("@ss.hasPermi('hazard:update') or @ss.hasPermi('hazard:improve')")
    @ApiOperation("修改隐患信息")
    @Log(title = "隐患信息", businessType = BusinessType.UPDATE)
    @PutMapping("/editHazard")
    public R<HazardInfoVo> update(@Validated @RequestBody HazardInfoVo vo) {
        if(vo.getId() == null){
            return R.fail("主键不能为空");
        }
        //限期为空 默认90天
        if("重大".equals(vo.getLevel()) ) {
            if(vo.getSuperviseLevel() == null){
                vo.setSuperviseLevel("省局督办");
            }
            if (vo.getDeadline() == null) {
                vo.setDeadline(DateUtils.addDays(vo.getCheckDate(), 90));
            }
        }
        else if("一般（黄）".equals(vo.getLevel()) && vo.getDeadline() == null){
            vo.setDeadline(DateUtils.addDays(vo.getCheckDate(), 30));
        }else if("一般（蓝）".equals(vo.getLevel()) && vo.getDeadline() == null){
            vo.setDeadline(DateUtils.addDays(vo.getCheckDate(), 5));
        }


        HazardInfo dbHazardInfo = hazardInfoService.getById(vo.getId());
        if(dbHazardInfo == null){
            return R.fail("隐患信息不存在");
        }
        //修改隐患信息的时候，不能修改attachmentsDocument2, attachmentsImage2, remark
        //2025-10-19 修改和整改的权限 也可以修改下面3个字段
//        vo.setAttachmentsDocument2(dbHazardInfo.getAttachmentsDocument2());
//        vo.setAttachmentsImage2(dbHazardInfo.getAttachmentsImage2());
//        vo.setRemark(dbHazardInfo.getRemark());
        HazardInfo hazardInfo = hazardInfoService.toEntity(vo);
        if(null == vo.getSuperviseLevel()) {
            hazardInfoService.updateSuperviseLevelToNull(hazardInfo);
        } else {
            hazardInfoService.updateById(hazardInfo);
        }
        vo = hazardInfoService.toVo(hazardInfo);
        return R.ok(vo);
    }
    @PreAuthorize("@ss.hasPermi('hazard:improve')")
    @ApiOperation("整改")
    @PutMapping("/improveHazard")
    public R<HazardInfoVo> improve(@Validated @RequestBody HazardInfoVo vo) {
        if(vo.getId() == null){
            return R.fail("主键不能为空");
        }
        HazardInfo dbHazardInfo = hazardInfoService.getById(vo.getId());
        if(dbHazardInfo == null){
            return R.fail("隐患信息不存在");
        }
        //整改隐患信息的时候，只能修改attachmentsDocument2, attachmentsImage2, remark
        dbHazardInfo.setAttachmentsDocument2(vo.getAttachmentsDocument2());
        dbHazardInfo.setAttachmentsImage2(vo.getAttachmentsImage2());
        dbHazardInfo.setRemark(vo.getRemark());
        hazardInfoService.updateById(dbHazardInfo);
        vo = hazardInfoService.toVo(dbHazardInfo);
        return R.ok(vo);
    }


//    @PreAuthorize("@ss.hasPermi('hazard:delete')")
//    @ApiOperation("删除隐患信息")
//    @DeleteMapping("/deleteHazard/{hazardId}")
//    @ApiImplicitParam(name = "hazardId", value = "隐患信息主键", required = true, dataType = "long", paramType = "path", dataTypeClass = Long.class)
//    public R<Void> delete(@PathVariable Long hazardId) {
//        HazardInfo dbHazardInfo = hazardInfoService.getById(hazardId);
//        if(dbHazardInfo == null){
//            return R.fail("隐患信息不存在");
//        }
//
//        boolean result =hazardInfoService.removeById(hazardId);
//        if(result){
//            return R.ok();
//        }
//        return R.fail("删除失败");
//    }


    @PreAuthorize("@ss.hasPermi('hazard:delete')")
    @ApiOperation("批量删除隐患信息")
    @PostMapping("/deleteHazard")
    @Log(title = "隐患信息", businessType = BusinessType.DELETE)
    @ApiImplicitParam(name = "hazardIds", value = "隐患信息主键集合", required = true, dataType = "List<Long>", paramType = "body", dataTypeClass = List.class)
    public R  delete(@RequestBody List<Long> hazardIds) {
        // 参数校验
        if (hazardIds == null || hazardIds.isEmpty()) {
            return R.fail("隐患信息主键集合不能为空");
        }
        // 校验ID有效性
        for (Long id : hazardIds) {
            if (id == null || id <= 0) {
                return R.fail("隐患信息主键无效");
            }
        }
        try {

            List<HazardInfo> dbHazardInfos = hazardInfoService.listByIds(hazardIds);
            if (dbHazardInfos.size() != hazardIds.size()) {
                return R.fail("部分隐患信息不存在");
            }
            // 批量删除
            boolean result = hazardInfoService.removeByIds(hazardIds);
            if (result) {
                return R.ok("批量删除成功");
            }
            return R.fail("批量删除失败");
        } catch (Exception e) {
            log.error("批量删除隐患信息异常", e);
            return R.fail("删除操作异常：" + e.getMessage());
        }
    }

    @PreAuthorize("@ss.hasPermi('hazard:finish')")
    @ApiOperation("整改完成/隐患销号")
    @PutMapping("/finishHazard/{hazardId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "hazardId", value = "隐患信息主键", dataType = "long", paramType = "path", dataTypeClass = String.class),
            @ApiImplicitParam(name = "finishDate", value = "整改完成日期(yyyy-MM-dd)", dataType = "String", required = true, dataTypeClass = String.class)
    })
    @Log(title = "隐患信息", businessType = BusinessType.UPDATE)
    public R<Void> finishHazard(@PathVariable Long hazardId,@RequestParam(value = "finishDate", required = true) String finishDate) {
        HazardInfo dbHazardInfo = hazardInfoService.getById(hazardId);
        if(dbHazardInfo == null){
            return R.fail("隐患信息不存在");
        }
        if(dbHazardInfo.getFinished()){
            return R.fail("隐患信息已整改完成");
        }
        if(StringUtils.equals(dbHazardInfo.getLevel(),"重大")){
            return R.fail("重大隐患信息需要督办整改");
        }
        dbHazardInfo.setFinished(true);
        dbHazardInfo.setFinishDate(DateUtils.parseDate(finishDate));
        //删除弹框预警信息
        hazardAlarmInfoService.remove(new LambdaQueryWrapper<HazardAlarmInfo>().eq(HazardAlarmInfo::getHazardId,hazardId));
        hazardInfoService.updateById(dbHazardInfo);
        return R.ok();
    }


//    @PreAuthorize("@ss.hasPermi('hazard:supervise')")
//    @ApiOperation("督办完成")
//    @PutMapping("/superviseHazard/{hazardId}")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "hazardId", value = "隐患信息主键", dataType = "long", paramType = "path", dataTypeClass = String.class),
//            @ApiImplicitParam(name = "finishDate", value = "整改完成日期(yyyy-MM-dd)", dataType = "String", required = true, dataTypeClass = String.class)
//    })
//    @Log(title = "隐患信息", businessType = BusinessType.UPDATE)
//    public R<Void> superviseHazard(@PathVariable Long hazardId,@RequestParam(value = "finishDate", required = true) String finishDate){
//         HazardInfo dbHazardInfo = hazardInfoService.getById(hazardId);
//         if(dbHazardInfo == null){
//             return R.fail("隐患信息不存在");
//         }
//         if(dbHazardInfo.getFinished()){
//             return R.fail("隐患信息已整改完成");
//         }
//         if(!StringUtils.equals(dbHazardInfo.getLevel(),"重大")){
//             return R.fail("隐患信息不是重大隐患，不需要督办整改");
//         }
//         dbHazardInfo.setFinished(true);
//         dbHazardInfo.setFinishDate(DateUtils.parseDate(finishDate));
//         hazardInfoService.updateById(dbHazardInfo);
//         return R.ok();
//    }

    @PreAuthorize("@ss.hasPermi('hazard:alarm')")
    @ApiOperation("隐患提醒-弹框")
    @PostMapping("/getHazardAlarm")
    @ApiImplicitParam(name = "deltaId", value = "最新提示隐患主键", dataType = "long", required = false, dataTypeClass = Long.class)
    public R<HazardAlarmVo> getHazardAlarm(@RequestParam(value = "deltaId", required = false) Long deltaId){
        Long deptId = SecurityUtils.getDeptId();
        HazardAlarmVo hazardAlarmVo = hazardInfoService.getHazardAlarm(deptId,deltaId);
        return R.ok(hazardAlarmVo);
    }



//    @PreAuthorize("@ss.hasPermi('hazard:hangup')")
//    @ApiOperation("挂起隐患信息")
//    @PutMapping("/hangupHazard/{hazardId}")
//    @ApiImplicitParam(name = "hazardId", value = "隐患信息主键", required = true, dataType = "long", paramType = "path", dataTypeClass = Long.class)
//    public R<Void> hangup(@PathVariable Long hazardId) {
//        HazardInfo dbHazardInfo = hazardInfoService.getById(hazardId);
//        if(dbHazardInfo == null){
//            return R.fail("隐患信息不存在");
//        }
//        if(StringUtils.equals(dbHazardInfo.getStatus(),"approved")){
//            return R.fail("隐患信息已审核通过，不允许挂起");
//        }
//        if(dbHazardInfo.getHangup()){
//            return R.fail("该隐患已是挂起状态");
//        }
//        dbHazardInfo.setHangup(true);
//        hazardInfoService.updateById(dbHazardInfo);
//        return R.ok();
//    }
//
//    @PreAuthorize("@ss.hasPermi('hazard:resum')")
//    @ApiOperation("恢复隐患")
//    @PutMapping("/resumHazard/{hazardId}")
//    @ApiImplicitParam(name = "hazardId", value = "隐患信息主键", required = true, dataType = "long", paramType = "path", dataTypeClass = Long.class)
//    public R<Void> resum(@PathVariable Long hazardId){
//        HazardInfo dbHazardInfo = hazardInfoService.getById(hazardId);
//        if(dbHazardInfo == null){
//            return R.fail("隐患信息不存在");
//        }
//        if(!StringUtils.equals(dbHazardInfo.getStatus(),"approved")){
//            return R.fail("隐患信息已审核通过，不允许恢复");
//        }
//        if(!dbHazardInfo.getHangup()){
//            return R.fail("该隐患已是恢复状态");
//        }
//        dbHazardInfo.setHangup(false);
//        hazardInfoService.updateById(dbHazardInfo);
//        return R.ok();
//    }


}
